package com.huaqin.obeacons;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.huaqin.obeacons.CalendarView.OnItemClickListener;
import com.huaqin.obeacons.adapter.ClockAdapter;
import com.huaqin.obeacons.utils.Clock;
import com.huaqin.obeacons.utils.MyDatabaseUtil;
import com.huaqin.obeacons.utils.Rotate3dAnimation;

public class HistoryFragment extends Fragment implements
		MyDatabaseUtil.DataListener,OnGestureListener {
	private static final int UPDATE_DATA = 0x111;
	private static final int NORMAL_MSG = 0X123;
	private static final int LATE_MSG = 0X124;
	private static final int EARLY_MSG = 0X125;
	private CalendarView calendar;
	private ImageButton leftButton;
	private ImageButton rightButton;
	private TextView calendarMonText;
	private LinearLayout shwoDetailLayout;
	private TextView showDetail;
	private ListView listView;
	private ViewFlipper viewFlipper;
	private ViewGroup timePickerViewGroup;
	private boolean showlineflag = true;
	private boolean isShowList = false;
	private Rotate3dAnimation mNextInAnimation;
	private Rotate3dAnimation mNextOutAnimation;
	private Rotate3dAnimation mPreviousInAnimation;
	private Rotate3dAnimation mPreviousOutAnimation;

	private int screenWidth = 0;
	private ImageView btnbackImageView;
	private TextView timetagdateTextView;
	private TextView timetagdetailTextView;
	private ListView timetagListView;
	private WorkStatus workstatus = WorkStatus.no_brush;

	// private SimpleAdapter simpleAdapter;
	private GestureDetector gestureDetector;
	
	public enum WorkStatus {
		no_brush, // 没有刷卡
		noraml_brush, // 正常刷卡
		late_brush, // 迟到刷卡
		early_brush, // 早退刷卡
		week_day_brush;// 周末
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case NORMAL_MSG:
				break;
			case LATE_MSG:
				break;
			case EARLY_MSG:
				break;
			case UPDATE_DATA:
				// if (listView != null && simpleAdapter != null)
				// listView.setAdapter(simpleAdapter);
				if (listView != null && lists != null && baseAdapter != null) {
					listView.setAdapter(baseAdapter);
				}
				updateLateTime();
				break;
			default:
				break;
			}
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_history, null);
		calendar = (CalendarView) view.findViewById(R.id.calendar);
		leftButton = (ImageButton) view.findViewById(R.id.calendarLeft);
		rightButton = (ImageButton) view.findViewById(R.id.calendarRight);
		calendarMonText = (TextView) view.findViewById(R.id.calendarCenter);
		shwoDetailLayout = (LinearLayout) view
				.findViewById(R.id.show_today_detail_layout);
		showDetail = (TextView) view.findViewById(R.id.show_today_detail);
		listView = (ListView) view.findViewById(R.id.detail_line);
		viewFlipper = (ViewFlipper) view.findViewById(R.id.viewFlipper);
		timePickerViewGroup = (ViewGroup) view
				.findViewById(R.id.timepicker_info);
		timetagdateTextView = (TextView) view
				.findViewById(R.id.timetag_date_text);
		timetagdetailTextView = (TextView) view
				.findViewById(R.id.timetag_detail_text);
		btnbackImageView = (ImageView) (view.findViewById(R.id.btn_list));
		timetagListView = (ListView) view.findViewById(R.id.timetag_list);
		timePickerViewGroup.animate().translationX(screenWidth).setDuration(20);
		timetagListView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				return gestureDetector.onTouchEvent(arg1);
			}
		});
		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		MyDatabaseUtil.getInstance(getActivity()).addDataListener(this);

		/* 定义DisplayMetrics对象 */
		DisplayMetrics dm = new DisplayMetrics();
		/* 取得窗口属性 */
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		/* 窗口的宽度 */
		screenWidth = dm.widthPixels;

		gestureDetector = new GestureDetector(getActivity(), this);
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onStart() {
		// 获取日历中年月 ya[0]为年，ya[1]为月（格式大家可以自行在日历控件中改）
		String[] ya = calendar.getYearAndmonth().split("-");
		calendarMonText.setText(ya[0] + " " + ya[1]);

		showlineflag = true;
		isShowList = false;
		calendar.setOnItemClickListener(new calendarItemClickListener());
		leftButton.setOnClickListener(new View.OnClickListener() {// 上一个月

					@Override
					public void onClick(View v) {
						String leftYearAndmonth = calendar.clickLeftMonth();
						String[] lya = leftYearAndmonth.split("-");
						calendarMonText.setText(lya[0] + " " + lya[1]);
						rightButton
								.setImageResource(R.drawable.calendar_month_right);
						leftButton
								.setImageResource(R.drawable.calendar_month_left_h);
						leftButton.setEnabled(false);
						showlineflag = false;
					}
				});
		rightButton.setOnClickListener(new View.OnClickListener() {// 查看打卡记录列表

					@Override
					public void onClick(View v) {
						if (!showlineflag) {
							String rightYearAndmonth = calendar
									.clickRightMonth();
							String[] rya = rightYearAndmonth.split("-");
							calendarMonText.setText(rya[0] + " " + rya[1]);
							rightButton
									.setImageResource(R.drawable.detail_show_line);
							leftButton
									.setImageResource(R.drawable.calendar_month_left);
							leftButton.setEnabled(true);
							showlineflag = true;
						} else {
							float f1 = viewFlipper.getWidth() / 2.0F;
							float f2 = viewFlipper.getHeight() / 2.0F;
							if (!isShowList) {
								rightButton
										.setImageResource(R.drawable.detail_show_calendar);
								leftButton.setEnabled(false);
								leftButton
										.setImageResource(R.drawable.calendar_month_left_h);
								isShowList = true;
								viewFlipper.setInAnimation(getNextInAnimation(
										f1, f2));
								viewFlipper
										.setOutAnimation(getNextOutAnimation(
												f1, f2));
								viewFlipper.showNext();
							} else {
								rightButton
										.setImageResource(R.drawable.detail_show_line);
								leftButton.setEnabled(true);
								leftButton
										.setImageResource(R.drawable.calendar_month_left);
								isShowList = false;
								viewFlipper
										.setInAnimation(getPreviousInAnimation(
												f1, f2));
								viewFlipper
										.setOutAnimation(getPreviousOutAnimation(
												f1, f2));
								viewFlipper.showPrevious();
							}
						}

					}
				});
		showDetail.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				MyDatabaseUtil.insertDateTimeHelp(getActivity());
			}
		});
		btnbackImageView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				viewFlipper.animate().translationX(0).setDuration(300);
				// timePickerViewGroup.setVisibility(View.GONE);
				shwoDetailLayout.animate().translationX(0).setDuration(300);
				timePickerViewGroup.animate().translationX(screenWidth)
						.setDuration(300);
			}
		});
		// updateLateTime();

		// Timer timer = new Timer();
		// TimerTask task = new TimerTask() {
		//
		// @Override
		// public void run() {
		// MyDatabaseUtil.insertDateTimeHelp(getActivity());
		// }
		// };
		// timer.schedule(task, 1000, 10000);

		updateDate();

		super.onStart();
	}

	private void updateLateTime() {// 更新缺勤时间
		String[] firstLastString = MyDatabaseUtil.getInstance(getActivity())
				.queryTodayFirstLastTime();
		Log.d("wuliqing", "firsttime = " + firstLastString[0] + " lasttime = "
				+ firstLastString[1]);
		String showString = getLateDetailString(firstLastString);
		calendar.drawTodayStatus(workstatus);

		showDetail.setText(showString);
	}

	private String getLateDetailString(String[] firstLastString) {
		String showString = null;
		if (firstLastString[0] != null && firstLastString[1] != null) {

			try {
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss", Locale.CHINA);
				Date firstDate = dateFormat.parse(firstLastString[0]);
				Date lastDate = dateFormat.parse(firstLastString[1]);

				Calendar cal = calendar.calendar;
				cal.setTime(firstDate);
				if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
						|| cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
					workstatus = WorkStatus.week_day_brush;
					return "休息日";
				}
				
				Date todayMorningStartWorkTimeDate0 = getTodayMorningStartWorkTime0(firstDate);
				// 上午上班时间8：30
				Date todayMorningStartWorkTimeDate = getTodayMorningStartWorkTime(firstDate);
				// 上午上班时间9：00
				Date todayMorningStopWorkTimeDate = getTodayMorningStopWorkTime(firstDate);
				// 上午下班时间12:00
				Date todayAfternoonStartworkTimeDate = getTodayAfternoonStartWorkTime(firstDate);
				// 下午上班时间13:00
				Date todayAfternoonStopworkTimeDate = getTodayAfternoonStopWorkTime(firstDate);
				// 下午下班时间17:30

				int morStartWorkResult0 = firstDate
						.compareTo(todayMorningStartWorkTimeDate0);
				int morStartWorkResult = firstDate
						.compareTo(todayMorningStartWorkTimeDate);
				int morStopWorkResult = firstDate
						.compareTo(todayMorningStopWorkTimeDate);
				int aftStartWorkResult = firstDate
						.compareTo(todayAfternoonStartworkTimeDate);
				int aftStopWorkResult = firstDate
						.compareTo(todayAfternoonStopworkTimeDate);

				Log.d("wuliqing", "morStartWorkResult = " + morStartWorkResult
						+ " morStopWorkResult = " + morStopWorkResult
						+ " aftStartWorkResult = " + aftStartWorkResult
						+ " aftStopWorkResult = " + aftStopWorkResult);

				int morStartWorkResult00 = lastDate
						.compareTo(todayMorningStartWorkTimeDate0);
				// int morStartWorkResult1 = lastDate
				// .compareTo(todayMorningStartWorkTimeDate);
				int morStopWorkResult1 = lastDate
						.compareTo(todayMorningStopWorkTimeDate);
				int aftStartWorkResult1 = lastDate
						.compareTo(todayAfternoonStartworkTimeDate);
				int aftStopWorkResult1 = lastDate
						.compareTo(todayAfternoonStopworkTimeDate);
				int aftStopWorkResult2 = (new Date())
						.compareTo(todayAfternoonStopworkTimeDate);

				if (aftStopWorkResult2 <= 0) {// 缺勤算法（未到下班时间）
					if (morStartWorkResult <= 0) {// 第一次刷卡时间小于上午上班时间
					// calendar.drawTodayStatus(WorkStatus.noraml_brush);
						workstatus = WorkStatus.noraml_brush;
						showString = "今天已正常刷卡！";
					} else if (morStartWorkResult > 0 && morStopWorkResult <= 0) {// 第一次刷卡时间大于上午上班时间小于上午下班时间
						showString = getLateDetail(firstDate,
								todayMorningStartWorkTimeDate, 0);
						// calendar.drawTodayStatus(WorkStatus.late_brush);
						workstatus = WorkStatus.late_brush;
					} else if (morStopWorkResult > 0 && aftStartWorkResult <= 0) {// 第一次刷卡时间大于上午下班小于下午上班时间
						showString = "缺勤3小时！";
						// calendar.drawTodayStatus(WorkStatus.late_brush);
						workstatus = WorkStatus.late_brush;
					} else if (aftStartWorkResult > 0 && aftStopWorkResult <= 0) {// 第一次刷卡时间大于下午上班时间小于下午下班时间
						showString = getLateDetail(firstDate,
								todayAfternoonStartworkTimeDate, 3);
						// calendar.drawTodayStatus(WorkStatus.late_brush);
						workstatus = WorkStatus.late_brush;
					} else if (aftStopWorkResult > 0) {// 第一次刷卡时间大于下午下班时间
						showString = "缺勤一天！";
						// calendar.drawTodayStatus(WorkStatus.late_brush);
						workstatus = WorkStatus.late_brush;
					}
				} else {// 早退算法（已到下班时间）
					if (firstDate.compareTo(lastDate) == 0) {// 当天只刷了一次卡
						if (aftStopWorkResult > 0) {// 刷卡时间大于下午下班时间
							showString = "缺勤一天！";
							workstatus = WorkStatus.late_brush;
						} else {
							showString = "您今天下班忘记刷卡！";
							workstatus = WorkStatus.early_brush;
						}
						// calendar.drawTodayStatus(WorkStatus.no_brush);
						
					} else if (morStartWorkResult0 < 0) {// 第一次刷卡小于8点30
						if (morStartWorkResult00 < 0) {// 最后一次刷卡小于8点30
							showString = "缺勤7小时30分钟！";
							// calendar.drawTodayStatus(WorkStatus.early_brush);
							workstatus = WorkStatus.early_brush;
						} else if (morStartWorkResult00 >= 0
								&& morStopWorkResult1 <= 0) {// 最后一次刷卡大于8点30，小于12点
							showString = getLateDetail(
									todayMorningStartWorkTimeDate0, lastDate,
									null, null, false);
							// calendar.drawTodayStatus(WorkStatus.early_brush);
							workstatus = WorkStatus.early_brush;
						} else if (morStopWorkResult1 > 0
								&& aftStartWorkResult1 < 0) {// 最后一次刷卡大于12点，小于1点
							showString = getLateDetail(
									todayMorningStartWorkTimeDate0,
									todayMorningStopWorkTimeDate, null, null,
									false);
							// calendar.drawTodayStatus(WorkStatus.early_brush);
							workstatus = WorkStatus.early_brush;
						} else if (aftStartWorkResult1 >= 0
								&& aftStopWorkResult1 <= 0) {// 最后一次刷卡大于1点，小于5点30
							showString = getLateDetail(
									todayMorningStartWorkTimeDate0,
									todayMorningStopWorkTimeDate,
									todayAfternoonStartworkTimeDate, lastDate,
									false);
							// calendar.drawTodayStatus(WorkStatus.early_brush);
							workstatus = WorkStatus.early_brush;
						} else if (aftStopWorkResult1 > 0) {// 最后一次刷卡大于5点30
							showString = getNomalWorkDetail(
									todayMorningStartWorkTimeDate0,
									todayMorningStopWorkTimeDate,
									todayAfternoonStartworkTimeDate, lastDate);
							// calendar.drawTodayStatus(WorkStatus.noraml_brush);
							workstatus = WorkStatus.noraml_brush;
						}
					} else if (morStartWorkResult0 >= 0
							&& morStartWorkResult < 0) {// 第一次刷卡大于8点30，小于9点
						if (morStartWorkResult00 >= 0
								&& morStopWorkResult1 <= 0) {// 最后一次刷卡大于8点30，小于12点
							showString = getLateDetail(firstDate, lastDate,
									null, null, false);
							// calendar.drawTodayStatus(WorkStatus.early_brush);
							workstatus = WorkStatus.early_brush;
						} else if (morStopWorkResult1 > 0
								&& aftStartWorkResult1 < 0) {// 最后一次刷卡大于12点，小于1点
							showString = getLateDetail(firstDate,
									todayMorningStopWorkTimeDate, null, null,
									false);
							// calendar.drawTodayStatus(WorkStatus.early_brush);
							workstatus = WorkStatus.early_brush;
						} else if (aftStartWorkResult1 >= 0
								&& aftStopWorkResult1 <= 0) {// 最后一次刷卡大于1点，小于5点30
							showString = getLateDetail(firstDate,
									todayMorningStopWorkTimeDate,
									todayAfternoonStartworkTimeDate, lastDate,
									false);
							// calendar.drawTodayStatus(WorkStatus.early_brush);
							workstatus = WorkStatus.early_brush;
						} else if (aftStopWorkResult1 > 0) {// 最后一次刷卡大于5点30
							showString = getNomalWorkDetail(firstDate,
									todayMorningStopWorkTimeDate,
									todayAfternoonStartworkTimeDate, lastDate);
							// calendar.drawTodayStatus(WorkStatus.noraml_brush);
							workstatus = WorkStatus.noraml_brush;
						}
					} else if (morStartWorkResult >= 0 && morStopWorkResult < 0) {// 第一次刷卡大于9点，小于12点
						if (morStartWorkResult >= 0 && morStopWorkResult1 <= 0) {// 最后一次刷卡大于9点，小于12点
							showString = getLateDetail(firstDate, lastDate,
									null, null, false);
							// calendar.drawTodayStatus(WorkStatus.late_brush);
							workstatus = WorkStatus.late_brush;
						} else if (morStopWorkResult1 > 0
								&& aftStartWorkResult1 < 0) {// 最后一次刷卡大于12点，小于1点
							showString = getLateDetail(firstDate,
									todayMorningStopWorkTimeDate, null, null,
									false);
							// calendar.drawTodayStatus(WorkStatus.late_brush);
							workstatus = WorkStatus.late_brush;
						} else if (aftStartWorkResult1 >= 0
								&& aftStopWorkResult1 <= 0) {// 最后一次刷卡大于1点，小于5点30
							showString = getLateDetail(firstDate,
									todayMorningStopWorkTimeDate,
									todayAfternoonStartworkTimeDate, lastDate,
									false);
							// calendar.drawTodayStatus(WorkStatus.late_brush);
							workstatus = WorkStatus.late_brush;
						} else if (aftStopWorkResult1 > 0) {// 最后一次刷卡大于5点30
							showString = getNomalWorkDetail(firstDate,
									todayMorningStopWorkTimeDate,
									todayAfternoonStartworkTimeDate, lastDate);
							// calendar.drawTodayStatus(WorkStatus.late_brush);
							workstatus = WorkStatus.late_brush;
						}
					} else if (morStopWorkResult >= 0 && aftStartWorkResult < 0) {// 第一次刷卡大于12点，小于1点
						if (morStopWorkResult1 > 0 && aftStartWorkResult1 < 0) {// 最后一次刷卡大于12点，小于1点
							showString = "您今天还未正常刷卡！";
							// calendar.drawTodayStatus(WorkStatus.no_brush);
							workstatus = WorkStatus.no_brush;
						} else if (aftStartWorkResult1 >= 0
								&& aftStopWorkResult1 <= 0) {// 最后一次刷卡大于1点，小于5点30
							showString = getLateDetail(
									todayAfternoonStartworkTimeDate, lastDate,
									null, null, false);
							// calendar.drawTodayStatus(WorkStatus.late_brush);
							workstatus = WorkStatus.late_brush;
						} else if (aftStopWorkResult1 > 0) {// 最后一次刷卡大于5点30
							showString = getLateDetail(
									todayAfternoonStartworkTimeDate,
									todayAfternoonStopworkTimeDate, null, null,
									true);
							// calendar.drawTodayStatus(WorkStatus.late_brush);
							workstatus = WorkStatus.late_brush;
						}
					} else if (aftStartWorkResult >= 0
							&& aftStopWorkResult <= 0) {// 第一次刷卡大于1点，小于5点30
						if (aftStartWorkResult1 >= 0 && aftStopWorkResult1 <= 0) {// 最后一次刷卡大于1点，小于5点30
							showString = getLateDetail(firstDate, lastDate,
									null, null, false);
							// calendar.drawTodayStatus(WorkStatus.late_brush);
							workstatus = WorkStatus.late_brush;
						} else if (aftStopWorkResult1 > 0) {// 最后一次刷卡大于5点30
							showString = getLateDetail(firstDate,
									todayAfternoonStopworkTimeDate, null, null,
									true);
							// calendar.drawTodayStatus(WorkStatus.late_brush);
							workstatus = WorkStatus.late_brush;
						}
					} else if (aftStopWorkResult > 0) {
						showString = "缺勤一天！";
						// calendar.drawTodayStatus(WorkStatus.no_brush);
						workstatus = WorkStatus.late_brush;
					}
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			// calendar.drawTodayStatus(WorkStatus.no_brush);
			workstatus = WorkStatus.no_brush;
			showString = "您今天还未刷卡！";
		}
		return showString;
	}

	private String getLateDetail(Date firstDate,
			Date todayAfternoonStartworkTimeDate, int late) {
		String showString;
		long s = firstDate.getTime();
		long s1 = todayAfternoonStartworkTimeDate.getTime();

		long hour = (long) ((s - s1) / (1000 * 60 * 60));
		long minute = (long) ((s - s1) / (1000 * 60) - hour * 60);
		long second = (long) ((s - s1) / (1000) - hour * 60 * 60 - minute * 60);

		showString = "缺勤" + (Math.abs(hour) + late) + "小时" + Math.abs(minute)
				+ "分" + Math.abs(second) + "秒！";
		return showString;
	}

	private String getLateDetail(Date startDate, Date endDate, Date startDate2,
			Date endDate2, boolean nomal) {
		String showString = null;
		if (startDate != null && endDate != null) {
			long s = startDate.getTime();
			long s1 = endDate.getTime();
			long microseconds = 8 * 60 * 60;
			long buf_s = Math.abs(s - s1);
			if (startDate2 != null && endDate2 != null) {
				long ss = startDate.getTime();
				long ss1 = endDate.getTime();
				buf_s = (Math.abs(s - s1) + Math.abs(ss - ss1));
			}

			long hour1 = (long) (buf_s / (1000 * 60 * 60));
			long minute1 = (long) (buf_s / (1000 * 60) - hour1 * 60);
			long second1 = (long) (buf_s / (1000) - hour1 * 60 * 60 - minute1 * 60);

			buf_s = hour1 * 60 * 60 + minute1 * 60 + second1;

			long _h = (microseconds - buf_s) / (60 * 60);
			long _m = (microseconds - buf_s) / 60 - _h * 60;
			long _s = microseconds - buf_s - _h * 60 * 60 - _m * 60;
			if (nomal) {
				showString = "缺勤" + _h + "小时" + _m + "分" + _s + "秒！";
			} else {
				showString = "缺勤" + _h + "小时" + _m + "分" + _s + "秒！";
			}
		}
		return showString;
	}

	private String getNomalWorkDetail(Date startDate, Date endDate,
			Date startDate2, Date endDate2) {
		String showString = null;
		if (startDate != null && endDate != null) {
			long s = startDate.getTime();
			long s1 = endDate.getTime();
			long microseconds = 8 * 60 * 60;// 8小时
			long microseconds_b = 30 * 60;// 半小时
			if (startDate2 != null && endDate2 != null) {
				long ss = startDate2.getTime();
				long ss1 = endDate2.getTime();

				long buf_s = Math.abs(s - s1) + Math.abs(ss - ss1);

				long hour1 = (long) (buf_s / (1000 * 60 * 60));
				long minute1 = (long) (buf_s / (1000 * 60) - hour1 * 60);
				long second1 = (long) (buf_s / (1000) - hour1 * 60 * 60 - minute1 * 60);

				buf_s = hour1 * 60 * 60 + minute1 * 60 + second1;
				if (buf_s > microseconds + microseconds_b) {// 上班时间大于8个半小时

					long _h = (buf_s - microseconds_b) / (60 * 60);
					long _m = (buf_s - microseconds_b) / 60 - _h * 60;
					long _s = buf_s - microseconds_b - _h * 60 * 60 - _m * 60;

					showString = "上班时间为" + _h + "小时" + _m + "分" + _s + "秒！";
					return showString;
				} else if (buf_s >= microseconds
						&& buf_s <= microseconds + microseconds_b) {// 大于8小时小于8个半小时
					return "您今天正常刷卡！";
				} else {
					return getLateDetail(startDate, endDate, startDate2,
							endDate2, true);
				}

			}
			long hour = (long) (((s - s1)) / (1000 * 60 * 60));
			long minute = (long) (((s - s1)) / (1000 * 60) - hour * 60);
			long second = (long) (((s - s1)) / (1000) - hour * 60 * 60 - minute * 60);

			showString = "上班时间为" + Math.abs(hour) + "小时" + Math.abs(minute)
					+ "分" + Math.abs(second) + "秒！";
		}
		return showString;
	}

	private Date getTodayMorningStartWorkTime0(Date date) {
		Date normalDateString = getWorkTimeHelp(date, 8, 30, 0, 0);
		return normalDateString;
	}

	private Date getTodayMorningStartWorkTime(Date date) {
		Date normalDateString = getWorkTimeHelp(date, 9, 0, 0, 0);
		return normalDateString;
	}

	private Date getTodayMorningStopWorkTime(Date date) {
		Date normalDateString = getWorkTimeHelp(date, 11, 59, 59, 0);
		return normalDateString;
	}

	private Date getTodayAfternoonStartWorkTime(Date date) {
		Date normalDateString = getWorkTimeHelp(date, 1, 0, 0, 1);
		return normalDateString;
	}

	private Date getTodayAfternoonStopWorkTime(Date date) {
		Date normalDateString = getWorkTimeHelp(date, 5, 30, 0, 1);
		return normalDateString;
	}

	private Date getWorkTimeHelp(Date date, int hour, int minute, int second,
			int am_pm) {
		// Date now = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR, hour);
		calendar.set(Calendar.MINUTE, minute);
		calendar.set(Calendar.SECOND, second);
		calendar.set(Calendar.AM_PM, am_pm);
		Date normalDate = calendar.getTime();
		return normalDate;
	}

	private void updateDate() {
		// List<Map<String, Object>> list = MyDatabaseUtil.getInstance(
		// getActivity()).queryData();
		// simpleAdapter = new SimpleAdapter(getActivity(), list,
		// R.layout.simpleadapter_item, new String[] { "date", "time" },
		// new int[] { R.id.simpleadapter_date, R.id.simpleadapter_time });
		//
		// handler.sendEmptyMessage(UPDATE_DATA);

		lists = MyDatabaseUtil.getInstance(getActivity()).queryDataList();
		baseAdapter = new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View view = getActivity().getLayoutInflater().inflate(
						R.layout.fragment_history_line, null);
				setHistoryView(position, view);
				return view;
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public Object getItem(int position) {
				return null;
			}

			@Override
			public int getCount() {
				if (lists != null) {
					return lists.size();
				}
				return 0;
			}

			@Override
			public int getItemViewType(int position) {
				return super.getItemViewType(position);
			}

			@Override
			public int getViewTypeCount() {
				return super.getViewTypeCount();
			}

		};
		handler.sendEmptyMessageDelayed(UPDATE_DATA, 300);
	}

	private List<List<Map<String, Object>>> lists = null;
	private BaseAdapter baseAdapter = null;

	private Rotate3dAnimation getNextInAnimation(float paramFloat1,
			float paramFloat2) {
		if (this.mNextInAnimation == null) {
			this.mNextInAnimation = new Rotate3dAnimation(-90.0F, 0.0F,
					paramFloat1, paramFloat2, 0.0F, false);
			this.mNextInAnimation.setDuration(300L);
			this.mNextInAnimation.setStartOffset(300L);
		}
		return this.mNextInAnimation;
	}

	private Rotate3dAnimation getNextOutAnimation(float paramFloat1,
			float paramFloat2) {
		if (this.mNextOutAnimation == null) {
			this.mNextOutAnimation = new Rotate3dAnimation(0.0F, 90.0F,
					paramFloat1, paramFloat2, 0.0F, false);
			this.mNextOutAnimation.setDuration(300L);
		}
		return this.mNextOutAnimation;
	}

	private Rotate3dAnimation getPreviousInAnimation(float paramFloat1,
			float paramFloat2) {
		if (this.mPreviousInAnimation == null) {
			this.mPreviousInAnimation = new Rotate3dAnimation(90.0F, 0.0F,
					paramFloat1, paramFloat2, 0.0F, false);
			this.mPreviousInAnimation.setDuration(300L);
			this.mPreviousInAnimation.setStartOffset(300L);
		}
		return this.mPreviousInAnimation;
	}

	private Rotate3dAnimation getPreviousOutAnimation(float paramFloat1,
			float paramFloat2) {
		if (this.mPreviousOutAnimation == null) {
			this.mPreviousOutAnimation = new Rotate3dAnimation(0.0F, -90.0F,
					paramFloat1, paramFloat2, 0.0F, false);
			this.mPreviousOutAnimation.setDuration(300L);
		}
		return this.mPreviousOutAnimation;
	}

	class calendarItemClickListener implements OnItemClickListener {
		@Override
		public void OnItemClick(Date date) {
			showTimerPicker(date);

		}
	}

	private int getTimeType(String timeString) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss",
				Locale.CHINA);
		try {
			Date normalDate = dateFormat.parse(timeString);
			Date Date0 = dateFormat.parse("8:30:00");
			// Date Date1 = dateFormat.parse("9:00:00");
			Date Date2 = dateFormat.parse("12:00:00");
			Date Date3 = dateFormat.parse("13:00:00");
			Date Date4 = dateFormat.parse("17:30:00");
			int com0 = normalDate.compareTo(Date0);
			// int com1 = normalDate.compareTo(Date1);
			int com2 = normalDate.compareTo(Date2);
			int com3 = normalDate.compareTo(Date3);
			int com4 = normalDate.compareTo(Date4);

			if (com0 < 0 || (com2 > 0 && com3 < 0) || com4 > 0) {
				return 1;
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public void notifyDataUpdate() {
		updateDate();
	}

	private void setHistoryView(int position, View view) {
		if (lists.size() != 0) {
			TextView daTextView = (TextView) view
					.findViewById(R.id.history_date);
			TextView timeTextView = (TextView) view
					.findViewById(R.id.history_time);

			LinearLayout listView = (LinearLayout) view
					.findViewById(R.id.history_brush_note);

			String daString = (String) (lists.get(position).get(position)
					.get("date"));

			String[] arrStrings = MyDatabaseUtil.getInstance(getActivity())
					.queryTodayFirstLastTime(daString);

			String showString = getLateDetailString(arrStrings);

			daTextView.setText(daString);
			timeTextView.setText(showString);

			List<Map<String, Object>> list = lists.get(position);

			for (int i = 0; i < list.size(); i++) {
				RelativeLayout relativeLayout = new RelativeLayout(
						getActivity());

				TextView textView = new TextView(getActivity());
				textView.setText((String) (list.get(i).get("time")));
				TextView textView1 = new TextView(getActivity());
				// ImageView imageView = new ImageView(getActivity());
				// imageView.setImageResource(R.drawable.tab_history_selected);

				RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
						RelativeLayout.LayoutParams.WRAP_CONTENT,
						RelativeLayout.LayoutParams.WRAP_CONTENT);
				layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
						RelativeLayout.TRUE);
				layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
				layoutParams.rightMargin = 30;

				textView.setLayoutParams(layoutParams);

				RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(
						RelativeLayout.LayoutParams.WRAP_CONTENT,
						RelativeLayout.LayoutParams.WRAP_CONTENT);
				layoutParams1.leftMargin = 20;
				// imageView.setLayoutParams(layoutParams1);
				textView1.setLayoutParams(layoutParams1);
				textView1.setTextColor(Color.WHITE);

				if (i == 0) {
					textView1.setText("上班");
					textView1.setBackgroundResource(R.drawable.bg_m_blue_icon);
				} else if (i == list.size() - 1) {
					textView1.setText("下班");
					textView1.setBackgroundResource(R.drawable.bg_m_red_icon);
				}

				// relativeLayout.addView(imageView);
				relativeLayout.addView(textView1);
				relativeLayout.addView(textView);

				listView.addView(relativeLayout);
			}

		}
	}

	@Override
	public boolean onDown(MotionEvent arg0) {
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float arg2,
			float arg3) {
		if (e1.getX() - e2.getX() > 100) {
		} else if (e2.getX() - e1.getX() > 100) {// 左——右
			viewFlipper.animate().translationX(0).setDuration(300);
			// timePickerViewGroup.setVisibility(View.GONE);
			shwoDetailLayout.animate().translationX(0).setDuration(300);
			timePickerViewGroup.animate().translationX(screenWidth)
					.setDuration(300);
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent arg0) {
		
	}

	@Override
	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent arg0) {
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent arg0) {
		return false;
	}

	private void showTimerPicker(Date date) {
		SimpleDateFormat dateformatter = new SimpleDateFormat(
				"yyyy年MM月dd日", Locale.CHINA);
		String datetString = dateformatter.format(date);
		List<Map<String, Object>> list = null;
		if (lists != null && lists.size() != 0) {
			for (int i = 0; i < lists.size(); i++) {
				list = lists.get(i);
				String str = (String) (list.get(i).get("date"));
				if (str != null && str.equals(datetString)) {
					break;
				} else {
					list = null;
					continue;
				}
			}
		}
		String[] arrStrings = MyDatabaseUtil.getInstance(getActivity())
				.queryTodayFirstLastTime(datetString);

		String showString = getLateDetailString(arrStrings);

		timetagdateTextView.setText(datetString);
		timetagdetailTextView.setText(showString);
		if (list != null && list.size() != 0) {
			List<Clock> clocks = new ArrayList<Clock>();
			for (int i = 0; i < list.size(); i++) {
				Clock clock = new Clock();
				clock.timeString = (String) (list.get(i).get("time"));
				// clock.status = getTimeType(clock.timeString);
				if (i == 0 || i == list.size() - 1)
					clock.status = 0;
				else {
					clock.status = 1;
				}
				clocks.add(clock);
			}
			ClockAdapter clockAdapter = new ClockAdapter(getActivity(),
					clocks);
			timetagListView.setAdapter(clockAdapter);

			viewFlipper.animate().translationX(-screenWidth)
					.setDuration(300);
			timePickerViewGroup.setVisibility(View.VISIBLE);
			timePickerViewGroup.animate().translationX(0).setDuration(300);
			shwoDetailLayout.animate().translationX(-screenWidth)
					.setDuration(300);
		} else {
			Toast.makeText(getActivity().getApplicationContext(),
					"无刷卡记录!", Toast.LENGTH_LONG).show();
		}
	}
}